import { ref } from 'vue'
import app from '@/app'
import { update } from '@/api/erp/supplier_order'
import supplierOrderStore from '../../../store/order'
import taxStore from '@/plugin/config/store/tax'

const store = {
  data: ref({}),
  goods: ref([]),

  getData() {
    return this.data.value
  },

  getGoods() {
    return this.goods.value
  },

  init(data) {
    this.data.value = Object.assign({
      supplier_id  : null,
      supplier_name: null,
      code         : app.time.code(),
      name         : '',
      money        : 0,
      count        : 0,
      goods        : []
    }, data)

    this.goods.value = data ? data.goods : []
    this.update()
  },

  // 更新统计
  update() {
    let money = 0,
    count = 0,
    total = 0,
    tax = 0

    // 循环商品
    this.getGoods().forEach(item => {
      // 税前总价
      item.money = app.math.mul(item.price, item.count)
      // 算出税后
      item.price_tax = app.math.addpro(item.price, item.tax)
      // 税后总价
      item.total = app.math.mul(item.price_tax, item.count)
      // 算出税额
      item.tax_money = app.math.sub(item.total, item.money)
      // 加入总价
      money = app.math.add(money, item.money)
      total = app.math.add(total, item.total)
      tax = app.math.add(tax, item.tax_money)
      // 数量统计
      count += item.count
    })

    // 保存总价和总数量
    this.getData().count = count
    this.getData().money = money
    this.getData().total = total
    this.getData().tax = tax

    console.log(this.getData())
  },

  // 新增栏
  async add(goods) {
    this.getGoods().push({
      id          : this.getGoods().length,
      goods_id    : goods.id,
      goods_number: goods.number,
      goods_name  : goods.name,
      goods_code  : goods.code,
      goods_image : goods.image,
      unit        : goods.unit,
      unit_count  : goods.unit_count,
      count       : 1,
      price       : goods.price_cost,
      price_tax   : 0,
      tax         : taxStore.tax(goods.tax_id),
      tax_money   : 0,
      money       : 0,
      total       : 0
    })

    this.update()
  },

  // 删除
  del(index) {
    this.getGoods().splice(index, 1)
    this.update()
  },

  // 提交
  post() {
    // 整理数据
    this.getData().goods = this.getGoods()
    return new Promise((resolve, jeject) => {
      update(this.getData()).then(res => {
        // 列表加载第一页
        supplierOrderStore.reset(1)
        // 重置数据
        this.init()
        resolve(res)
      }).catch(res => {
        jeject(res)
      })
    })
  }
}

// 首次执行
store.init()

// 税率加载
taxStore.get()

export default store